from . import view
from . import schema
from fastapi import APIRouter, Depends, Security
from package.connector.sql_db import db
from package.fastapi import permission

router_source = APIRouter(prefix='/source', tags=['数据源'])
router_meta = {'module': '数据采集', 'sub_module': '数据源'}


@router_source.get('/', response_model=schema.PageSource, openapi_extra=router_meta, name='source_list_get',
                   summary='数据源列表')
def source_get(q: str = None,
               page: int = 1,
               page_size: int = 10,
               order_by: str = None,
               session=Depends(db.get_session),
               user=Security(permission.get_user_funcable, scopes=[])):
    return view.source.get_page_items(session, q=q, page=page, page_size=page_size, order_by=order_by)


@router_source.post('/', response_model=schema.SourceOut, openapi_extra=router_meta, name='source_post',
                    summary='数据源创建')
def source_post(body: schema.Source,
                session=Depends(db.get_session),
                user=Security(permission.get_user_funcable, scopes=[])):
    return view.source.create_item(session, body=body.dict())


@router_source.get('/{id}', response_model=schema.SourceOut, openapi_extra=router_meta, name='source_get',
                   summary='数据源详情')
def source_get(id: str,
               session=Depends(db.get_session),
               user=Security(permission.get_user_funcable, scopes=[])):
    return view.source.get_item(session, id=id)


@router_source.patch('/{id}', response_model=schema.SourceOut, openapi_extra=router_meta, name='source_patch',
                     summary='数据源修改')
def source_patch(id: str,
                 body: schema.EditSource,
                 session=Depends(db.get_session),
                 user=Security(permission.get_user_funcable, scopes=[])):
    return view.source.update_item(session, body.dict(exclude_unset=True), id=id)


@router_source.delete('/', openapi_extra=router_meta, name='source_delete', summary='数据源删除')
def source_delete(body: schema.BatchId,
                  session=Depends(db.get_session),
                  user=Security(permission.get_user_funcable, scopes=[])):
    return {'count': view.source.delete_items(session, body.ids)}


@router_source.post('/verify', openapi_extra=router_meta, name='source_verify', summary='数据源验证')
def source_verify(body: schema.Source,
                  session=Depends(db.get_session),
                  user=Security(permission.get_user_funcable, scopes=[])):
    return
